package com.cskaoyan.controller.backgroundsystemcontroller;

import cn.dev33.satoken.stp.StpUtil;
import com.cskaoyan.bean.bo.AuthInfoBo;
import com.cskaoyan.bean.bo.AuthLoginBo;
import com.cskaoyan.bean.bo.LoginByEmailBo;
import com.cskaoyan.bean.bo.ProfilePasswordBo;
import com.cskaoyan.bean.pojo.Logout;
import com.cskaoyan.bean.pojo.LogoutExample;
import com.cskaoyan.bean.pojo.admin.Admin;
import com.cskaoyan.bean.vo.AdminDashboardVo;
import com.cskaoyan.bean.vo.AuthDobbyVo;
import com.cskaoyan.bean.vo.AuthInfoVo;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.dao.LogoutMapper;
import com.cskaoyan.exception.DataDisplayException;
import com.cskaoyan.realm.MallToken;
import com.cskaoyan.service.AdminService;
import com.cskaoyan.utils.EmailUtil;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;


/**
 * @author: lds
 * @clsss: AuthController
 */
@RestController
public class AuthController {

    @Autowired
    AdminService adminService;
    @Autowired
    EmailUtil emailUtil;
    @Autowired
    LogoutMapper logoutMapper;

    /**
     * @author: lds
     * @title: authLogin
     * @description:
     * @param: [authLoginBo]
     * @return: com.cskaoyan.bean.vo.WxBaseRespVo
     */
    @RequestMapping("admin/auth/login")
    //使用 @RequiresPermissions需要aspectj
    //引入aspectjweaver的支持包
    //需要注册一个advicer
    //登录所具有的权限，        多个权限        权限之间的关系是or
    /*
     * 使用 @RequiresPermissions需要有aspectj的支持
     * 引入aspectj引入adviceor
     * */
    public BaseRespVo authLogin(HttpServletRequest request, @RequestBody AuthLoginBo authLoginBo) {
//        System.out.println("login");
//        System.out.println(authLoginBo);
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(new MallToken(authLoginBo.getUsername(), authLoginBo.getPassword(), "admin"));
        } catch (Exception e) {
            return BaseRespVo.fail("用户帐号或密码不正确");
        }
        Serializable id = subject.getSession().getId();

        boolean authenticated = subject.isAuthenticated();
        System.out.println(authenticated);

        return BaseRespVo.ok((String) id);

    }

    /**
     * @author: lds
     * @title: authInfo
     * @description:
     * @param: [token]
     * @return: com.cskaoyan.bean.vo.WxBaseRespVo
     */
    @RequestMapping("admin/auth/info")
//    @RequiresPermissions(value = {"*"}, logical = Logical.OR)
    public BaseRespVo authInfo(String token) {
        System.out.println(token);

        Subject subject = SecurityUtils.getSubject();
        Admin primaryPrincipal = (Admin) subject.getPrincipals().getPrimaryPrincipal();
        System.out.println(primaryPrincipal.getId());
        String username = primaryPrincipal.getUsername();
        String password = primaryPrincipal.getPassword();
        try {
            subject.login(new MallToken(username, password, "admin"));
        } catch (Exception e) {

            return BaseRespVo.fail("用户帐号或密码不正确");
        }
        AuthInfoBo authInfoBo = new AuthInfoBo(username, password);
        AuthInfoVo authInfoVo = adminService.queryAdmin(authInfoBo);
        System.out.println(authInfoVo);
        return BaseRespVo.ok(authInfoVo);

    }

    /**
     * @author: lds
     * @title: adminDashboard
     * @description: 查找info页面所需要的信息
     * @param: []
     * @return: com.cskaoyan.bean.vo.WxBaseRespVo
     */

    @RequestMapping("admin/dashboard")
    public BaseRespVo adminDashboard() throws DataDisplayException {
        AdminDashboardVo adminDashboardVo = adminService.queryInfoMessage();
        if (adminDashboardVo == null) {
            throw new DataDisplayException();
        } else {
            return BaseRespVo.ok(adminDashboardVo);
        }


    }


    /**
     * @author: lds
     * @title: authLogout
     * @description:
     * @param: []
     * @return: com.cskaoyan.bean.vo.WxBaseRespVo
     */
    @RequestMapping("admin/auth/logout")
    public BaseRespVo authLogout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipals().getPrimaryPrincipal();
        Integer integer = adminService.removePwd(admin);
        System.err.println(integer);
        subject.logout();
        return BaseRespVo.ok();

    }

    /**
     * @author: lsy lds
     * @title: dobby
     * @description: 应当响应该用户上次登陆的时间和ip
     * @param: [username, password]
     * @return: java.lang.String
     */
    @GetMapping("admin/auth/dobby")

    public BaseRespVo dobby(String username, String password) {// TODO 响应该用户上次登陆的时间和ip

        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        String lastLoginIp = admin.getLastLoginIp();
        String host = subject.getSession().getHost();
        if (lastLoginIp.equals(host)) {

            AuthDobbyVo authDobbyVo = new AuthDobbyVo();
            authDobbyVo.setIp(admin.getLastLoginIp());
            authDobbyVo.setLastTime(admin.getLastLoginTime());
            authDobbyVo.setIsSameIp(true);

            return BaseRespVo.ok(authDobbyVo);

        } else {
            AuthDobbyVo authDobbyVo = new AuthDobbyVo();
            authDobbyVo.setIp(admin.getLastLoginIp());
            authDobbyVo.setLastTime(admin.getLastLoginTime());
            authDobbyVo.setIsSameIp(false);

            Date date = new Date(System.currentTimeMillis());
            System.out.println(host);
            Integer integer = adminService.changeIpAndLoginTime(admin, host, date);
//            emailUtil.verificationCode(admin.);
//            System.err.println("2222222");
            Serializable id = subject.getSession().getId();
            emailUtil.changeCode(admin.getEmail(),id.toString());
            return BaseRespVo.ok2(authDobbyVo);

        }

    }



    @GetMapping("admin/auth/sendEmail")
    public BaseRespVo sendEmail(String email) {
        String verificationCode = emailUtil.verificationCode(email);
        //插入验证码
        Integer integer = adminService.addPwd(email, verificationCode);
        return BaseRespVo.ok();

    }

    @PostMapping("admin/auth/loginByEmail")
    public BaseRespVo loginByEmail(@RequestBody LoginByEmailBo loginByEmailBo) {

        String email = loginByEmailBo.getEmail();
        String pwd = loginByEmailBo.getPwd();
        Admin admin = adminService.queryAdminExit(email, pwd);
        if (admin.getPwd()==null){
            return BaseRespVo.fail("验证码错误");
        }
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(new MallToken(admin.getUsername(), admin.getPassword(), "admin"));
        } catch (Exception e) {
            return BaseRespVo.fail("没有此用户");
        }
        Serializable id = subject.getSession().getId();
        String host = subject.getSession().getHost();

        boolean authenticated = subject.isAuthenticated();
        System.out.println(authenticated);
        return BaseRespVo.ok((String) id);

    }






    @PostMapping("profile/password")
    public BaseRespVo profilePassword(@RequestBody ProfilePasswordBo profilePasswordBo){
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        String password = admin.getPassword();
        String oldPassword = profilePasswordBo.getOldPassword();

        if (password.equals(oldPassword)){
            Integer integer = adminService.changePassword(admin, profilePasswordBo);
            return BaseRespVo.ok("密码修改成功");
        }else {
            return BaseRespVo.fail("密码错误");
        }
    }
    @RequestMapping("logout/kickout")
     public BaseRespVo logoutKickout(String token){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();


//测试权限框架
//        LogoutExample logoutExample = new LogoutExample();


//        Logout logout = new Logout();
//        String s=null;
//        logout.setToken(token);
//        logoutMapper.insertSelective(logout);
//
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.setViewName("kickout.jsp");
//        System.err.println("11111111111");
//
//        System.err.println(token);
        return BaseRespVo.ok();
    }















}